const {mysql} = require('../../qcloud')

//在goods获取各种信息（ goods/goods.vue/goodsDetail 方法）
async function detailAction(ctx){
	const {openId,goodsId} = ctx.request.query
	//获取商品信息
	const info = await mysql('nideshop_goods').where({'id': goodsId}).select()
	//获取商品轮播图图片
	const gallery = await mysql('nideshop_goods_gallery').where({
  'goods_id': goodsId
  })
  //获取商品参数
  // 关联查询两张表leftJoin
  const attribute = await mysql('nideshop_goods_attribute')
  	.column('nideshop_goods_attribute.value', 'nideshop_attribute.name')
  	.leftJoin('nideshop_attribute', 'nideshop_goods_attribute.attribute_id', 'nideshop_attribute.id')
    .where({
        'nideshop_goods_attribute.goods_id': goodsId
    }).select()
	//常见问题
	const issue = await mysql('nideshop_goods_issue').select()
  //判断商品是否被收藏
  const iscollect = await mysql('nideshop_collect').where({
    'user_id':openId,
    'value_id': goodsId
  }).select()
  let collected =false
  //如果有该记录，说明商品被收藏
  if(iscollect.length > 0){
    collected = true
  }
  //判断购物车是否含有商品
  const oldNumber = await mysql('nideshop_cart').where({
    'user_id': openId
  }).column('number').select()
    let allnumber = 0
    if (oldNumber.length > 0) {
      for (let i = 0; i < oldNumber.length; i++) {
        const element = oldNumber[i] 
        allnumber += element.number
      }
    }

  	ctx.state.data = {
  		info,gallery,attribute,issue,collected,allnumber
  	}
}

// 商品列表(不需要的)
async function goodsList(ctx) {
  const categoryId = ctx.query.categoryId
  let goodsList = []
  if (categoryId) {
    goodsList = await mysql('nideshop_goods').where({
      'category_id': categoryId
    }).select()
    //当前被点击分类信息
    const currentNav = await mysql('nideshop_category').where({
      'id': categoryId
    }).select()

    if (goodsList.length == 0) {
      // 找到与之相关的子类，再找到与子类相关的商品
      // 找到和当前点击的总分类id相同的parent_id的数据
      let subIds = await mysql('nideshop_category').where({
        'parent_id': categoryId
      }).column('id').select()
      if (subIds.length !== 0) {
        //返回该parent_id的id
        subIds = subIds.map((item) => {
          return item.id
        })
      }
      //再到商品表中根据category_id和返回的parent_id的id相比较相等则取出
      goodsList = await mysql('nideshop_goods').whereIn('category_id', subIds).limit(20).select()
    }

    ctx.state.data = {
      goodsList: goodsList,
      currentNav: currentNav[0]
    }
  }
}

module.exports = {
	detailAction,
  goodsList
}